#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/7/7 4:08
# @Author : LZQ
# @Version：V 0.1
# @File : commons.py
# @desc :
# ocding utf-8
from werkzeug.routing import BaseConverter
from flask import session, jsonify, g,current_app
from app.utils.status_code import RET
import functools


# 定义正则转换器
class ReConverter(BaseConverter):
    ''''''

    def __init__(self, url_map, regex):
        super().__init__(url_map)
        self.regex = regex


def login_required(view_func):
    @functools.wraps(view_func)
    def wrapper(*args, **kwargs):
        user_id = session.get("user_id")
        user_city = session.get("user_city")
        if user_id is not None:
            g.user_id = user_id
            g.user_city = user_city
            return view_func(*args, **kwargs)
        else:
            return jsonify(RET.SESSION_ERROR)

    return wrapper


def tree(leve1_list, leve2_list, leve3_list):
    data = []
    if leve1_list:
        for leve1 in leve1_list:
            # 循环遍历顶级的菜单
            leve1_dict = {}
            leve1_dict['authName'] = leve1.ps_name
            leve1_dict['id'] = leve1.ps_id
            leve1_dict['children'] = []
            for leve2 in leve2_list:
                # 循环遍历二级的菜单
                leve2_dict = {}
                leve2_dict['authName'] = leve2.ps_name
                leve2_dict['id'] = leve2.ps_id
                leve2_dict['children'] = []
                for leve3 in leve3_list:
                    # 循环遍历三级的菜单
                    leve3_dict = {}
                    leve3_dict['authName'] = leve3.ps_name
                    leve3_dict['id'] = leve3.ps_id
                    if leve2.ps_id == leve3.ps_pid:
                        leve2_dict['children'].append(leve3_dict)
                if leve1.ps_id == leve2.ps_pid:
                    leve1_dict['children'].append(leve2_dict)
            data.append(leve1_dict)
    elif leve2_list:
        for leve2 in leve2_list:
            # 循环遍历二级的菜单
            leve2_dict = {}
            leve2_dict['authName'] = leve2.ps_name
            leve2_dict['id'] = leve2.ps_id
            leve2_dict['children'] = []
            for leve3 in leve3_list:
                # 循环遍历三级的菜单
                leve3_dict = {}
                leve3_dict['authName'] = leve3.ps_name
                leve3_dict['id'] = leve3.ps_id
                if leve2.ps_id == leve3.ps_pid:
                    leve2_dict['children'].append(leve3_dict)
                    leve3_list.remove(leve3)
            data.append(leve2_dict)
    else:
        for leve3 in leve3_list:
            # 循环遍历三级的菜单
            leve3_dict = {}
            leve3_dict['authName'] = leve3.ps_name
            leve3_dict['id'] = leve3.ps_id
            data.append(leve3_dict)
    return data



